import React, { useState, useMemo, useEffect } from 'react';
import { obj_int, obj_str, show_mt, is_empty, HandView, ColView, Btn, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, BtTxt,
    save_data, InfoDlg, Bar, uJob, cline, PanelFind, loc } from 'sui';
import { update_sale, load_custom, load_col, get_ck, load_sale } from './cmd';
import { load_tech } from 'task/cmd';
import { DlgNum } from './ctl';
import { Census } from './census';
import { useAccess } from 'cache';

const TaskView = () => {
    const [open_info, openInfo] = useState(false);
    const [open_num, openNum] = useState(false);
    const [col, setCol] = useState();
    const [tech, setTech] = useState();
    const [main, setMain] = useState();
    const [custom, setCustom] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();
    const [no_acc] = useAccess();

    useEffect(() => {
        load_custom(setCustom);
        load_tech(setTech);
        load_col(setCol);

        load_sale(null, setMain);
    }, []);

    const getRow = useMemo(() => {
        const lst = ["sn", "custom", "tech", "pend"];
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const getCol = useMemo(() => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 160, formatter: (props) => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "dnum")} disabled={no_acc("ta")}>{loc("l_504")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "fin")} disabled={no_acc("ta")}>{loc("l_526")}</BtTxt>
                    </div>
                );
            }},
        ];

        col.forEach(d => {
            if (d.sn === "dnum") {
                tmp.push({name: d.name, key: d.sn, width: 100, formatter: (props) => {
                    const d = props.row;
                    const dnum = obj_int(d, "dnum");

                    let cl = "blue";
                    if (dnum <= 0) {
                        cl = "green";
                    }

                    return <Bar flag={dnum} cl={cl}/>;
                }});
            } else {
                show_mt(tmp, d, 156);
            }
        });

        return tmp;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [col]);

    if (umd.isFin("census")) {
        const getName = () => {
            const t = umd.cur;
            if (t === "tech") {
                return loc("l_363");
            }

            return loc("l_520");
        };

        const getTitle = () => {
            const t = umd.cur;
            if (t === "tech") {
                return loc("l_527");
            }

            return loc("l_530");
        };

        return <Census hreturn={() => umd.hreturn()} title={getTitle()} data={main} mod={umd.cur} name={getName()}/>;
    }

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];
        col.forEach(d => {
            if (d.sn === "sn") {
                d.ctp = "auto";
            } else if (d.sn === "tech") {
                d.ctl = tech;
            } else if (d.sn === "custom") {
                d.ctl = custom;
            }

            ret.push(d);
        });

        return ret;
    };

    const act = {
        "add": (v, h) =>  update_sale(umd, v, h, setMain),
        "dnum": v =>  {
            umd.startWait();

            uJob(null, "sale/out",
                {
                    line: cline(),
                    k: obj_str(umd.cur, "sn"),
                    num: obj_int(v, "dnum"),
                },
                r => load_sale(umd.endWait, setMain),
                e => umd.setErr());
        },
        "fin": () =>  {
            const sn = obj_str(umd.cur, "sn");
            if (!sn) {
                return;
            }

            umd.startWait();

            uJob(null, "sale/fin",
                {
                    line: cline(),
                    k: sn,
                },
                r => load_sale(umd.endWait, setMain),
                e => umd.setErr());
        },
    };

    const pact = {
        "dnum": () => openNum(true),
        "fin": () => openInfo(true),
    };

    const hreturn = () => {
        load_col(setCol);
        umd.hreturn();
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: "sangle", name: loc("l_516")},
        ];

        return <ColView hreturn={hreturn} title={loc("l_454")} subtitle={loc("l_221")} list={list} cur="sangle"/>;
    }
    else if (umd.isFin("add")) {
        return <HandView umd={umd} title={loc("l_454")} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const hExport = () => {
        save_data(main, getCol, `${loc("l_454")}`, umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn hcmd={hExport} className="ml-4" disabled={no_acc("ta")}>{loc("l_298")}</Btn>
            <Btn className="mx-4" color="green" hcmd={() => umd.pact(null, null, "add")} disabled={no_acc("ta")}>{loc("l_239")}</Btn>
            <Btn hcmd={() => umd.pact(null, null, "col")} disabled={no_acc("ta")}>{loc("l_221")}</Btn>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            {loc("l_454")}
            <Btn hcmd={() => umd.pact(null, "tech", "census")} color="teal" className="ml-8">{loc("l_527")}</Btn>
            <Btn hcmd={() => umd.pact(null, "custom", "census")} color="teal" className="ml-4">{loc("l_530")}</Btn>
        </div>
    );

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={getCol} row={getRow} high={high}/>
            <DlgNum open={open_num} setOpen={openNum} data={umd.cur} hcmd={v => umd.act(act, v)}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_859")} hcmd={() => umd.act(act)} hcancel={() => openInfo(false)}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {TaskView};
